package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 菜品业务层
 */
@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    /**
     * 新增菜品和风味
     *
     * @param dishDTO
     */

    @Override
    @Transactional
    public void insertDishAndFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.insert(dish);
        //此处需要使用主键返回
        Long dishId = dish.getId();
        log.info("主键返回的dishId:{}", dishId);
        List<DishFlavor> flavors = dishDTO.getFlavors();
        //默认每次修改都删除口味 因为下面会判空 TODO 要记住逻辑
        dishFlavorMapper.deleteFlavorByDishId(dishId);
        //口味的判空，因为口味是非必须的
        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(flavor -> flavor.setDishId(dishId));
            dishFlavorMapper.insert(flavors);
        }

    }

    /**
     * 菜品的条件分页查询
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        List<DishVO> dishVOList = dishMapper.pageQuery(dishPageQueryDTO);
        Page<DishVO> dishVOPage = (Page<DishVO>) dishVOList;
        return new PageResult(dishVOPage.getTotal(), dishVOPage.getResult());
    }

    /**
     * 菜品删除逻辑实现
     *
     * @param ids
     */
    @Override
    @Transactional
    public void deleteDish(List<Long> ids) {
        //起售中的菜品不能删除
        for (Long id : ids) {
            Integer dishStatus = dishMapper.selectStatusById(id);
            //判断当前要删除的菜品状态是否为起售中
            if (dishStatus != null && dishStatus == 1) {
                //如果是起售中，抛出业务异常
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        //被套餐关联的菜品不能删除
        for (Long id : ids) {
            Long setMealId = setmealDishMapper.getSetmealIdsByDishId(id);
            //判断当前要删除的菜品是否被套餐关联了
            if (setMealId != null) {
                //如果关联了，抛出业务异常
                throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
            }
        }
        //既不是起售中的菜品也不是被套餐关联的菜品，直接从菜品表删除同时删除关联的口味数据
        for (Long id : ids) {
            dishMapper.deleteDishById(id);
            dishFlavorMapper.deleteFlavorByDishId(id);
        }
    }

    /**
     * 即根据id查询菜品
     * 同时查询菜品的口味信息
     *
     * @param id
     * @return
     */
    @Override
    public DishVO findDishById(Long id) {
        //根据id在dish表中查询菜品信息
        Dish dish = dishMapper.findDishById(id);
        //根据dishId查询菜品的口味信息
        List<DishFlavor> dishFlavorList = dishFlavorMapper.findFlavorsByDishId(id);

        //数据的封装
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(dishFlavorList);
        return dishVO;
    }

    /**
     * 修改菜品信息
     *
     * @param dishDTO
     */
    @Override
    @Transactional
    public void updateDish(DishDTO dishDTO) {
        //修改菜品表的信息
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.update(dish);

        List<DishFlavor> flavors = dishDTO.getFlavors();

        //默认每次修改都删除口味 因为下面会判空
        Long dishId = dish.getId();
        //删除原有的口味
        dishFlavorMapper.deleteFlavorByDishId(dishId);
        //口味的判空，因为口味是非必须的
        if (flavors != null && flavors.size() > 0) {
            //对于口味的数据，先删除原有的口味再插入新的口味数据

            log.info("获取到的菜品id:{}", dishId);



            //给口味集合中的口味都设置菜品id
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dishId);
            }
            //插入修改过后的口味
            dishFlavorMapper.insert(flavors);
        }
    }

    /**
     * 根据name查询菜品
     *
     * @param name
     * @param categoryId
     * @return
     */
    @Override
    public List<DishVO> selectDishByNameAndCategoryId(String name, Long categoryId) {
        List<DishVO> dishList = dishMapper.selectDishByNameAndCategoryId(name, categoryId);
        return dishList;
    }

    /**
     * 更改菜品的售卖状态(菜品起售、停售)
     *
     * @param status
     * @param id
     */
    @Override
    public void updateDishStatus(Integer status, Long id) {
        dishMapper.updateDishStatus(status, id);
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.findFlavorsByDishId(d.getId());
            log.info("查到的口味数据为：{}",flavors);
            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
